package timingtask

import (
	"app-box/config"
	"app-box/tools/app_log"
	"io/ioutil"
	"os"
	"path/filepath"
	"time"

	"github.com/robfig/cron/v3"
)

func Start() {
	c := cron.New(cron.WithParser(cron.NewParser(cron.Second | cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow)))
	/// 每天0点删除旧的文件
	if _, err := c.AddFunc("0 0 0 * * *", deleteTempFile); err != nil {
		app_log.Fatal(err.Error())
	}
	c.Start()
}

func deleteTempFile() {
	tmpPath := filepath.Join(config.LocalFile.FilaSavePath, "tmp")
	files, err := ioutil.ReadDir(tmpPath)
	if err != nil {
		app_log.Error("delete temp file failed:", err.Error())
		return
	}
	app_log.Log("start delete tmp file")
	date := time.Now()
	yesterday := date.Format("2006-01-02")
	oneDay, _ := time.ParseDuration("-24h")
	beforYesterday := date.Add(oneDay).Format("2006-01-02")

	app_log.Log("file", yesterday, "and", beforYesterday, "will not be delete")
	for _, item := range files {
		// 不是昨天，也不是前天的文件夹，统统删除
		if item.IsDir() && item.Name() != yesterday && item.Name() != beforYesterday {
			app_log.Log("delete", item.Name())
			if err := os.RemoveAll(filepath.Join(tmpPath, item.Name())); err != nil {
				app_log.Error("delete", item.Name(), "failed")
			}
		}
	}
}
